package cn.itcast.web.controller.cargo;

import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;

import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;


    /*
           作用： 进入出货表页面
           url: /cargo/contract/print.do
           参数：没有
           返回值 :出货表页面
        */
    @RequestMapping("/print")
    public String print() {
        return "cargo/print/contract-print";
    }


    /*
          作用： 下载出货表
          url: /cargo/contract/printExcel.do?inputDate=2015-01
          参数：inputDate 出货日期
          返回值 : 无，因为是下载

          注意： 如果一个方法是下载文件的时候，必须使用@ResponseBody
       */
    @RequestMapping("/printExcel")
    @ResponseBody  //返回字符串、 返回json、下载
    public void printExcel(String inputDate) throws IOException {

        //1. 读取模板的输入流 , 读取webapp目录下的资源记得是使用ServletContext
        InputStream inputStream = session.getServletContext().getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");

        //2. 使用模块的输入流创建一个工作薄

        Workbook workbook = new SXSSFWorkbook();

        //得到工作单
        Sheet sheet = workbook.getSheetAt(0);


        //3.设置标题内容
        String title = inputDate.replaceAll("-0", "年").replaceAll("-", "年") + "月份出货表";
        //获取第0行
        Row row = sheet.getRow(0);
        //获取1个单元格
        Cell cell = row.getCell(1);
        //设置单元格的内容
        cell.setCellValue(title);

        //4. 提取第二行的样式出来存储到数组中，提供给后面的数据去使用
        CellStyle[] cellStyles = new CellStyle[8];

        //获取第二行
        row = sheet.getRow(2);

        //遍历数组
        for (int i = 0; i < cellStyles.length; i++) {
            cell = row.getCell(i + 1);
            cellStyles[i] = cell.getCellStyle();
        }
        //定义一个变量保存索行
        int index = 2;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        //获取到货物的数据
        List<ContractProductVo> contractProductVoList = contractProductService.findByShipTime(inputDate,getLoginUserCompanyId());
        //遍历所有的货物的数据
        if (contractProductVoList != null) {


            for (ContractProductVo contractProductVo : contractProductVoList) {
                //每一个货物的数据就是一行
                row = sheet.createRow(index++);

                // 客户名称
                String customName = contractProductVo.getCustomName();

                if (customName != null) {
                    cell = row.createCell(1);

                    //设置单元格样式

                    cell.setCellStyle(cellStyles[0]);

                    //设置内容

                    cell.setCellValue(customName);


                }

                // 订单号
                String contractNo = contractProductVo.getContractNo();
                if (contractNo != null) {

                    cell = row.createCell(2);

                    //设置单元格样式
                    cell.setCellStyle(cellStyles[1]);

                    //设置内容
                    cell.setCellValue(contractNo);

                }

                //货号
                String productNo = contractProductVo.getProductNo();
                if (productNo != null) {
                    cell = row.createCell(3);
                    //设置单元格样式
                    cell.setCellStyle(cellStyles[2]);
                    //设置内容
                    cell.setCellValue(productNo);
                }


                // 数量
                Integer cnumber = contractProductVo.getCnumber();
                if (cnumber != null) {

                    cell = row.createCell(4);

                    //设置单元格样式
                    cell.setCellStyle(cellStyles[3]);

                    //设置内容
                    cell.setCellValue(cnumber);

                }

                // 工厂
                String factoryName = contractProductVo.getFactoryName();
                if (factoryName != null) {
                    cell = row.createCell(5);
                    //设置单元格样式
                    cell.setCellStyle(cellStyles[4]);
                    //设置内容
                    cell.setCellValue(factoryName);
                }


                // 客户名称
                Date deliveryPeriod = contractProductVo.getDeliveryPeriod();
                if (deliveryPeriod != null) {
                    cell = row.createCell(6);
                    //设置单元格样式
                    cell.setCellStyle(cellStyles[5]);
                    //设置内容
                    cell.setCellValue(simpleDateFormat.format(deliveryPeriod));
                }


                // 客户名称
                Date shipTime = contractProductVo.getShipTime();
                if (shipTime != null) {
                    cell = row.createCell(7);
                    //设置单元格样式
                    cell.setCellStyle(cellStyles[6]);
                    //设置内容
                    cell.setCellValue(simpleDateFormat.format(shipTime));
                }


                //货号
                String tradeTerms = contractProductVo.getTradeTerms();
                if (tradeTerms != null) {
                    cell = row.createCell(8);
                    //设置单元格样式
                    cell.setCellStyle(cellStyles[7]);
                    //设置内容
                    cell.setCellValue(tradeTerms);
                }

            }

        }

        //字节数组输出流，该类的本质就是内部维护一个字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //把工作簿数据写入到ByteArrayOutputStream中
        workbook.write(byteArrayOutputStream);
        new DownloadUtil().download(byteArrayOutputStream, response, "出货表.xlsx");


    }





    //下面是百万数据导出的方法

/*


    @RequestMapping("/printExcel")
    @ResponseBody  //返回字符串、 返回json、下载
    public void printExcel(String inputDate) throws IOException {
        //1. 创建工作薄
        Workbook workbook = new SXSSFWorkbook();
        //2. 创建工作单S
        Sheet sheet = workbook.createSheet("出货表");

        //3. 合并单元格

       */
/* CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
               firstRow： 开始行
                lastRow:  结束行
                firstCol:  开始列
                lastCol:   结束列*//*


        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
        //4. 设置列宽
        sheet.setColumnWidth(0, 6 * 256);
        sheet.setColumnWidth(1, 21 * 256);
        sheet.setColumnWidth(2, 16 * 256);
        sheet.setColumnWidth(3, 29 * 256);
        sheet.setColumnWidth(4, 11 * 256);
        sheet.setColumnWidth(5, 11 * 256);
        sheet.setColumnWidth(6, 11 * 256);
        sheet.setColumnWidth(7, 11 * 256);
        sheet.setColumnWidth(8, 11 * 256);
        sheet.setColumnWidth(9, 11 * 256);


        //标题 第0行  2015-01  2015年1  2015-11
        String title = inputDate.replaceAll("-0", "年").replaceAll("-", "年") + "月份出货表";
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(1);
        //设置单元格样式
        cell.setCellStyle(bigTitle(workbook));
        //设置内容
        cell.setCellValue(title);


        //表头部分
        String[] titles = {"客户", "订单号", "货号", "数量", "工厂", "工厂交期", "船期", "贸易条款"};
        row = sheet.createRow(1);
        for (int i = 0; i < titles.length; i++) {
            //创建单元格
            cell = row.createCell(i + 1);
            //设置样式
            cell.setCellStyle(title(workbook));
            //设置内容
            cell.setCellValue(titles[i]);
        }

        //定义一个变量保存索行
        int index = 2;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        //获取到货物的数据
        List<ContractProductVo> contractProductList = contractProductService.findByShipTime(inputDate, getLoginUserCompanyId());
        if (contractProductList != null) {
            for (int i = 0; i < 5800; i++) {


                //遍历所有的货物的数据
                for (ContractProductVo contractProductVo : contractProductList) {
                    //每一个货物的数据就是一行
                    row = sheet.createRow(index++);

                    // 客户名称
                    String customerName = contractProductVo.getCustomName();
                    if (customerName != null) {
                        cell = row.createCell(1);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(customerName);
                    }


                    // 订单号
                    String contractNo = contractProductVo.getContractNo();
                    if (contractNo != null) {
                        cell = row.createCell(2);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(contractNo);
                    }


                    //货号
                    String productNo = contractProductVo.getProductNo();
                    if (productNo != null) {
                        cell = row.createCell(3);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(productNo);
                    }


                    // 数量
                    Integer cnumber = contractProductVo.getCnumber();
                    if (cnumber != null) {
                        cell = row.createCell(4);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(cnumber);
                    }


                    // 工厂
                    String factoryName = contractProductVo.getFactoryName();
                    if (factoryName != null) {
                        cell = row.createCell(5);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(factoryName);
                    }


                    // 客户名称
                    Date deliveryPeriod = contractProductVo.getDeliveryPeriod();
                    if (deliveryPeriod != null) {
                        cell = row.createCell(6);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(simpleDateFormat.format(deliveryPeriod));
                    }


                    // 客户名称
                    Date shipTime = contractProductVo.getShipTime();
                    if (shipTime != null) {
                        cell = row.createCell(7);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(simpleDateFormat.format(shipTime));
                    }

                    //货号
                    String tradeTerms = contractProductVo.getTradeTerms();
                    if (tradeTerms != null) {
                        cell = row.createCell(8);
                        //设置单元格样式
                        //cell.setCellStyle(text(workbook));
                        //设置内容
                        cell.setCellValue(tradeTerms);
                    }

                }

            }

           */
/* //下载乱码的时候我们可以使用url编码
            String fileName = "出货表.xlsx";
            fileName = URLEncoder.encode(fileName, "UTF-8");

            //通知浏览器以附件下载的形式处理内容
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            //获取到浏览器的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);*//*



            */
/*download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName)
                    byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
                    response：响应对象
                    returnName : 下载文件的名字*//*


            //字节数组输出流，该类的本质就是内部维护一个字节数组
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            //把工作簿数据写入到ByteArrayOutputStream中
            workbook.write(byteArrayOutputStream);
            new DownloadUtil().download(byteArrayOutputStream, response, "出货表.xlsx");


        }
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);                //横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short) 10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);                //横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);        //纵向居中
        style.setBorderTop(BorderStyle.THIN);                        //上细线
        style.setBorderBottom(BorderStyle.THIN);                    //下细线
        style.setBorderLeft(BorderStyle.THIN);                        //左细线
        style.setBorderRight(BorderStyle.THIN);                        //右细线

        return style;
    }
*/


}
